import React from 'react';
import classnames from 'classnames';

/**
 *
    <RePopover
         className="my-popover"
         isShow={this.state.isShow}
         triangleIsShow={false}
         triangleAlign="left">
        <div style={{'width':'200','height':'400'}}>child</div>
    </RePopover>
 *
 */

export default class view extends React.Component {
    static propTypes = {
        rootClassName: React.PropTypes.string,
        popoverClassName: React.PropTypes.string,
        tabIndex: React.PropTypes.number,
        isShow: React.PropTypes.bool.isRequired,
        triangleIsShow: React.PropTypes.bool,
        triangleAlign: React.PropTypes.string,
        trigger: React.PropTypes.element,
        onBlur: React.PropTypes.func
    };

    static defaultProps = {
        tabIndex: 0,
        isShow: false,
        triangleIsShow: false,
        triangleAlign: 'center',
        onBlur: () => {}
    }

    constructor(props, context) {

        super(props, context);

        // init state;
        this.state = {
            isShow: props.isShow,
            triangleIsShow: props.triangleIsShow,
            triangleAlign: props.triangleAlign,
            shouldTriggerBlur: true
        };
    }
    componentWillMount() {
        this._isMounted = true;
    }

    componentDidMount() {}

    componentWillReceiveProps(nextProps) {
        this.setState({
            isShow: nextProps.isShow,
        });
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

    renderTriangle() {
        let triangleClassNames = classnames({
            'orin-sw-repopover-triangle':true,
            [this.props.triangleAlign]:true
        });
        return <div className={triangleClassNames} />;
    }

    handleMouseEnter() {
        this.setState({ shouldTriggerBlur: false });
    }

    handleMouseLeave() {
        this.setState({ shouldTriggerBlur: true });
    }

    handleBlur() {
        this.state.shouldTriggerBlur && this.props.onBlur();
    }

    render() {
        return (
            <div
                className={classnames({
                    'orin-sw-repopover-root': true,
                    [this.props.rootClassName || '']: true
                })}
                tabIndex={this.props.tabIndex}
                onMouseEnter={this.handleMouseEnter.bind(this)}
                onMouseLeave={this.handleMouseLeave.bind(this)}
                onBlur={this.handleBlur.bind(this)}>
                {this.props.trigger}

                <div
                    className={classnames({
                        'orin-sw-repopover-wrapper': true,
                        'show':this.state.isShow,
                        [this.props.popoverClassName || '']: true
                    })}>
                    {this.props.triangleIsShow ? this.renderTriangle() : null}
                    <div className="orin-sw-repopover-children">{this.props.children}</div>
                </div>

            </div>
        );
    }
}
